package me.zixing.java.chapter11.server;

import java.io.*;
import java.net.Socket;
import java.util.logging.FileHandler;

/**
 * Created by bingh on 2017/12/1.
 */
public class ServerHandler extends Thread{
    private Socket Socket;

    public ServerHandler(Socket socket) {
        Socket = socket;
    }

    public Socket getSocket() {
        return Socket;
    }

    public void setSocket(Socket socket) {
        Socket = socket;
    }

    @Override
    public void run() {
        //处理流
        try{
            InputStream inputStream = getSocket().getInputStream();
            byte[] b = new byte[1024];
            int i = 0;
            String requestFilePath = "";

            while((i=inputStream.read(b))!=-1){
                requestFilePath += new String(b,0,i);
            }

            System.out.println(requestFilePath);
            FileInputStream fileInputStream =
                    FileFinder.getFileInputStreamByPath(requestFilePath);
            if(fileInputStream == null){
                OutputStream outputStream = getSocket().getOutputStream();
                outputStream.write("没有该文件".getBytes());
                outputStream.flush();
                outputStream.close();

            }else{
                OutputStream outputStream = getSocket().getOutputStream();
                byte[] fb = new byte[1024];
                int fi = 0;
                while((fi = fileInputStream.read(fb)) != -1){
                    outputStream.write(fb,0,fi);
                }
                outputStream.flush();
                outputStream.close();
            }
        }catch (IOException e){
            e.printStackTrace();
        }

    }
}
